package com.chap8;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * <p>
 * <code>ReadWriteLockExample</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-03-23 8:53
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class ReadWriteLockExample4 {
    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    private final Lock readLock = lock.readLock();
    private final Lock writeLock = lock.writeLock();
    private final String[] data = new String[10];

    public void write(int index,String value){
        writeLock.lock();
        try{
            System.out.println(Thread.currentThread().getName()+"获取写锁");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException();
            }
            //写的期间有一个读操作
            read(2);
            data[index] = value;
        }finally {
            System.out.println(Thread.currentThread().getName()+"释放写锁");
            writeLock.unlock();
        }
    }

    public String read(int index){
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"获取读锁");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException();
            }
            return data[index];
        }finally {
            System.out.println(Thread.currentThread().getName()+"释放读锁");
            readLock.unlock();
        }
    }
    public static void main(String[] args) {
        ReadWriteLockExample4 rwl = new ReadWriteLockExample4();
        new Thread(()->{
            rwl.write(2,"eeee");
        }).start();

    }
}
/*
Thread-0获取写锁
Thread-0获取读锁
Thread-0释放读锁
Thread-0释放写锁

获取写锁之后可以获取读锁
*/